<!--
 * @description:
 * @author: cuicui
 * @Date: 2023-11-26 12:14:15
 * @LastEditTime: 2023-12-02 09:29:44
 * @LastEditors: cuicui
-->
<template>
  <a-modal
    :title='model ? "编辑角色" : "新增角色"'
    :width='640'
    :visible='visible'
    :confirmLoading='loading'
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning='loading'>
      <a-form :form='form' v-bind='formLayout'>
        <a-form-item label='id' v-show='false'>
          <a-input v-decorator="['id']" />
        </a-form-item>
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item label='角色名称'>
          <a-input
            placeholder='请输入角色名称'
            v-decorator="['rolename', {rules: [{ required: true, message: '请输入角色名称' },
                        { pattern: namePattern,  message: '请输入合法内容(可输入0到50位（中文、字母，数字，下划线，减号)'}], validateTrigger: 'blur'}]" />
        </a-form-item>
        <!--        <a-form-item label='角色编码'>-->
        <!--          <a-input-->
        <!--            placeholder='请输入角色编码'-->
        <!--            v-decorator="['roleCode', {rules: [{ required: true, message: '请输入角色编码' }], validateTrigger: 'blur'}]" />-->
        <!--        </a-form-item>-->
        <a-form-item label='设置权限'>
          <a-tree-select
            placeholder='请设置权限'
            treeDefaultExpandAll
            :maxTagCount='5'
            multiple
            treeCheckStrictly
            v-decorator="['permissionIds', {rules: [{ required: true, message: '请设置权限' } ]}]"
            style='width: 100%'
            :replaceFields='{ children:"subPermission", title:"permissionName", key: "id", value: "id"}'
            :tree-data='permissionTree'
            tree-checkable
            :show-checked-strategy='SHOW_ALL'
          />
        </a-form-item>
        <a-form-item label='备注'>
          <a-textarea
            v-decorator="['roledesc']"
            placeholder='请输入角色备注' :auto-size='{ minRows: 3, maxRows: 5 }' />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { getBase64 } from '@/utils/util'
import pick from 'lodash.pick'

// 表单字段
import { strPattern1 as roleNamePattern, namePattern } from '@/reges'
import { TreeSelect } from 'ant-design-vue'
import { findPermissionTree } from '@/api/permission'

const SHOW_ALL = TreeSelect.SHOW_ALL

const fields = ['roledesc', 'roleCode', 'rolename', 'id', 'permissionIds']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data() {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      SHOW_ALL,
      namePattern,
      roleNamePattern,
      permissionTree: [],
      imageUrl: '',
      form: this.$form.createForm(this)
    }
  },
  created() {
    this.findPermissionTree()
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  methods: {
    findPermissionTree() {
      findPermissionTree().then(res => {
        this.permissionTree = res
      })
    },
    filterOptionFun(inputValue, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
      )
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.uploadLoading = true
        return
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl
          this.uploadLoading = false
        })
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJpgOrPng && isLt2M
    }
  }
}
</script>

<style lang='less'>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
